#!/bin/sh
if [ "$2" = ns ];then
	if [ -n "$3" ];then
		while ! nslookup $3 >/dev/null 2>&1;do
			sleep 1
		done
	fi
	if [ -n "$4" ];then
		while ! nslookup $4 >/dev/null 2>&1;do
			sleep 1
		done
	fi
fi

if [ "$1" = gfw ];then
	B=$(uci -q get bypass.@global[0].pre_ip) || B=1
	if [ $B = 1 ];then
		B=1
		while ! A=$(nslookup -q=TXT _spf.google.com | grep text | sed -e 's/"v=spf1//' -e 's/ ~all"//' -e 's/ include:/\n/g' | grep -v text);do
			[ $B -ge 20 ] && break || let B++
			sleep 2
		done
		for i in $A;do
			B=1
			while ! nslookup -q=TXT $i >/dev/null 2>&1;do
				[ $B -ge 20 ] && break || let B++
				sleep 2
			done
			B=$(nslookup -q=TXT $i | sed -e 's/"v=spf1//' -e 's/ ~all"//' -e 's/ ip.:/\n/g' | grep -E -o '([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]{1,2}')
			for i in $B;do ipset add blacklist $i 2>/dev/null;done
		done
		B=1
		while ! A=$(curl -Lfsm 9 https://cdn.jsdelivr.net/gh/f6UiINtMDSmglMK4/A9xehMB2/ht2ix0v4Aj/Fnx8osN6xh | base64 -d || curl -Lfsm 9 https://raw.githubusercontent.com/f6UiINtMDSmglMK4/A9xehMB2/master/ht2ix0v4Aj/Fnx8osN6xh | base64 -d);do
			[ $B -ge 20 ] && break || let B++
			sleep 2
		done
		for i in $A;do ipset add blacklist $i 2>/dev/null;done
	fi
	
	B=1
	while (curl --retry 3 -m 5 216.239.38.120 >/dev/null 2>&1 && ! curl --retry 3 -m 5 https://google.com && true) >/dev/null 2>&1;do
		echo "$(date +'%Y-%m-%d %H:%M:%S') : ipset lost,restart bypass..." >>/tmp/log/bypass.log
		/etc/rc.d/bypass restart
		[ $B -ge 10 ] && break || let B++
		sleep 2
	done

fi
